package yl.hs.bmipfull.service.material.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.material.IRawMaterialInventoryDao;
import yl.hs.bmipfull.daos.material.IRawMaterialTransferDao;
import yl.hs.bmipfull.daos.vehiclemanage.ITruckInfoDao;
import yl.hs.bmipfull.pojo.material.RawMaterialInventoryEntity;
import yl.hs.bmipfull.pojo.material.RawMaterialTransferOrderEntity;
import yl.hs.bmipfull.pojo.vehiclemanage.TruckInfoEntity;
import yl.hs.bmipfull.service.material.IRMTransferService;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.SubmitModel;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/*
 * RMTransferServiceImpl
 * @category
 * @author 谢景广
 * @date 2022-12-23
 */
@Service
public class RMTransferServiceImpl extends PurchaseBaseService implements IRMTransferService {

    @Override
    @Transactional
    public Integer saveSign(SubmitModel model) {
        var entity = transferDao.findBySN(model.getSn());
        var user = HsApp.getCurrent();
        entity.setSignTime(new Date());
        assert user != null;
        entity.setSignUserSN(user.getUserSN());
        entity.setSignUserName(user.getUserName());
        entity.setSignPic(model.getData().get("pic").toString());
        entity.setSignSVG(model.getData().get("svg").toString());
        entity.setSignRemark(model.getData().get("remark").toString());
        entity.setState((short) 8);
        var result = transferDao.update(entity);
        if (result>0){
            var inventory = inventoryDao.findByWHSNAndRmSN(entity.getReceiptWhSN(), entity.getRmSN());
            if (inventory == null) {
                inventory = new RawMaterialInventoryEntity();
                inventory.setQuantity(entity.getNetWeight());
                inventory.setRmSN(entity.getRmSN());
                inventory.setWhSN(entity.getReceiptWhSN());
                inventoryDao.insertNew(inventory);
            } else {
                inventory.setQuantity(entity.getNetWeight().add(inventory.getQuantity()));
                inventoryDao.update(inventory);
            }
            var truck = truckDao.findByTruck(entity.getTruckPlate());
            truck.setWeight(true);
            truck.setState((short) 40);
            truckDao.update(truck);
            writeLog(ActionType.UPDATE,entity.getSn(),"调拨签收","",entity.getClass());
        }
        return result;
    }

    @Override
    public Integer saveTareWeight(String sn, BigDecimal weight) {
        var entity = transferDao.findBySN(sn);
        entity.setTareWeight(weight);
        entity.setBackTime(new Date());
        var result = transferDao.update(entity);
        if (result>0){
            var truck = truckDao.findByTruck(entity.getTruckPlate());
            truck.setWeight(true);
            truck.setState((short) 0);
            truckDao.update(truck);
            writeLog(ActionType.UPDATE,sn,"车辆回皮","",entity.getClass());
        }
        return result;
    }


    @Override
    @Transactional
    public Integer saveGrossWeight(String sn, BigDecimal weight) {
        var entity = transferDao.findBySN(sn);
        entity.setGrossWeight(weight);
        entity.setNetWeight(entity.getGrossWeight().subtract(entity.getTareWeight()));
        entity.setOutTime(new Date());
        entity.setState((short) 1);
        var result = transferDao.update(entity);
        if (result>0){
            var inventory = inventoryDao.findByWHSNAndRmSN(entity.getShipWhSN(), entity.getRmSN());
            if (inventory == null) {
                inventory = new RawMaterialInventoryEntity();
                inventory.setQuantity(entity.getNetWeight().multiply(BigDecimal.valueOf(-1)));
                inventory.setRmSN(entity.getRmSN());
                inventory.setWhSN(entity.getShipWhSN());
                inventoryDao.insertNew(inventory);
            } else {
                inventory.setQuantity(inventory.getQuantity().subtract(entity.getNetWeight()));
                inventoryDao.update(inventory);
            }
           var truck = truckDao.findByTruck(entity.getTruckPlate());
            truck.setWeight(false);
            truck.setState((short) 30);
            truckDao.update(truck);
            writeLog(ActionType.UPDATE,sn,"车辆过毛出厂","",entity.getClass());
        }
        return result;
    }

    @Override
    public Integer savePlan(SubmitModel model) throws Exception {
        RawMaterialTransferOrderEntity entity;
        var result  = 0;
        if(Tl.isEmpty(model.getSn())){
            entity = new RawMaterialTransferOrderEntity();
            Tl.getChangeLog(entity,model.getData());
            entity.setAddTime(new Date());
            entity.setSn(queryNewSN(entity.getClass()));
            result = transferDao.insertNew(entity);
            if(result >0){

                writeLog(ActionType.CREATE,entity.getSn(),"创建调拨计划","",entity.getClass());
            }
        }
        else{
            entity = transferDao.findBySN(model.getSn());
            if(entity!=null){
                var backJson = entity.toJson();
                var log = Tl.getChangeLog(entity,model.getData());
                result = transferDao.update(entity);
                if(result>0){
                    writeLog(ActionType.UPDATE,entity.getSn(),"更新调拨单数据:"+log,backJson,entity.getClass());
                }
            }
        }
        if(result>0){
            var truck = truckDao.findByTruck(entity.getTruckPlate());
            if(truck==null){
                truck = new TruckInfoEntity();
                truck.setTruckFrom((short)1);
                truck.setState((short)0);
                truck.setTruckPlate(entity.getTruckPlate());
                truck.setTruckCode("调拨"+entity.getTruckPlate());
                truck.setLoadWeight(50.0d);
                truck.setInsuranceAmount(BigDecimal.ZERO);
                truck.setAverageFuelConsumption(BigDecimal.ZERO);
                truck.setTareWeight(0.0);
                truck.setWeight(true);
                truck.setUseType("RMTransferTruck");
                truck.setAverageFuelConsumptionLastMonth(BigDecimal.ZERO);
                truck.setBackTime(new Date());
                truck.setLatestMileage(BigDecimal.ZERO);
                truck.setSortCode(0L);
                truck.setSn(queryNewSN(truck.getClass()));
                truck.setCardSNO("test01");
                truckDao.insertNew(truck);
            }else{
                truck.setUseType("RMTransferTruck");
                truck.setWeight(true);
                truck.setTruckFrom((short)1);
                truck.setState((short)0);
                truck.setSortCode(0L);
                truckDao.update(truck);
            }

        }
        return result;
    }

    @Override
    public RawMaterialTransferOrderEntity findBySn(String sn) {
        return transferDao.findBySN(sn);
    }

    @Override
    public Integer backAndReturn(String sn) {
        var entity = transferDao.findBySN(sn);

        entity.setState((short) 2);
        var result  = transferDao.update(entity);
        if(result>0){
            var inventory = inventoryDao.findByWHSNAndRmSN(entity.getShipWhSN(), entity.getRmSN());
            if (inventory == null) {
                inventory = new RawMaterialInventoryEntity();
                inventory.setQuantity(entity.getNetWeight());
                inventory.setRmSN(entity.getRmSN());
                inventory.setWhSN(entity.getShipWhSN());
                inventoryDao.insertNew(inventory);
            } else {
                inventory.setQuantity(entity.getNetWeight().add(inventory.getQuantity()));
                inventoryDao.update(inventory);
            }
            writeLog(ActionType.UPDATE,entity.getSn(),"作废调拨单，并退回出库原材","",entity.getClass());
        }
        return result;
    }

    @Override
    public Integer deleteBySN(String sn) throws JsonProcessingException {
        var entity = transferDao.findBySN(sn);
        entity.setState((short) -1);
        var result  = transferDao.update(entity);
        if(result>0) {
            writeLog(ActionType.DELETE,entity.getSn(),"删除调拨信息",entity.toJson(),entity.getClass());
        }
        return result;
    }

    @Override
    public PageResult<RawMaterialTransferOrderEntity> queryPage(PageQuery query, int rowNum, int page) {
        query.checkSortSides(RawMaterialTransferOrderEntity.class);
        var filters = SearchFilterEngine.generateQueryList(query.getFilters(), RawMaterialTransferOrderEntity.class);
        PageResult<RawMaterialTransferOrderEntity>   result = new PageResult<>(rowNum);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        result.setRecords(transferDao.queryCountByCondition(query.getQuery(),filters));
        result.setPage(page);
        result.setData(transferDao.queryPage(query.getQuery(),filters));
        return result;
    }

    @Override
    public List<RawMaterialTransferOrderEntity> queryPlan() {
        return transferDao.queryAllPlan();
    }

    @Override
    public RawMaterialTransferOrderEntity findByTruck(String truckPlate) {
        return transferDao.findByTruck(truckPlate);
    }

    @Override
    public List<RawMaterialTransferOrderEntity> queryAll(String key) {
        return transferDao.queryAll(key);
    }

    IRawMaterialInventoryDao inventoryDao;

    @Autowired
    public void setInventoryDao(IRawMaterialInventoryDao inventoryDao) {
        this.inventoryDao = inventoryDao;
    }

    private IRawMaterialTransferDao transferDao;

    @Autowired
    public void setTransferDao(IRawMaterialTransferDao transferDao) {
        this.transferDao = transferDao;
    }

    private ITruckInfoDao truckDao;

    @Autowired
    public void setTruckDao(ITruckInfoDao truckDao) {
        this.truckDao = truckDao;
    }
}
